# -*- encoding: utf-8 -*-
# @Time       :  16:04
# @Author     : yuxian
# @Email      : 1503889663@qq.com
# @File       : verify.py
# @SoftWare   : PyCharm
import os
import random
import string
from PIL import Image, ImageFont, ImageDraw, ImageFilter


class ImageVerify:
    """图像验证码类"""

    def __init__(self, length=4, width=140, height=40, size=28):
        """
        初始化图片信息
        :param length: 字符个数
        :param width: 图片宽度
        :param height: 图片高度
        :param size: 字符大小
        """
        self.length = length
        self.width = width
        self.height = height
        self.size = size

    def random_str(self):
        """
        随机字符串
        26大小写字母+10个数字作为数据源（奖池）
        :return:
        """
        source = string.ascii_letters + ''.join([str(i) for i in range(0, 10)])
        return ''.join(random.sample(source, self.length))

    def random_color(self, start=0, end=255):
        """随机RGB颜色"""
        res = (random.randint(start, end) for i in range(3))
        return tuple(res)

    def random_lines(self, draw):
        """
        绘制干扰线
        :param draw: 画笔
        :return:
        """
        for i in range(self.length):
            lines = [(random.randint(0, self.width), random.randint(0, self.height)) for i in range(2)]
            draw.line(list(lines), fill=self.random_color(64, 250), width=2)

    def random_points(self, draw, rate):
        """
        绘制噪点
        :param draw: 画笔
        :param rate: 频率
        :return:
        """
        for x in range(self.width):
            for y in range(self.height):
                if random.randint(1, 100) <= rate:
                    draw.point((x, y), fill=self.random_color(end=200))

    def verify_code(self):
        """
        生成验证码图片
        :return:
        """
        # 创建画布，Image对象 底图
        image = Image.new('RGB', (self.width, self.height), (255, 255, 255))  # (颜色通道,(宽,高),(R,G,B))

        # 创建Font对象
        file_path = os.path.dirname(os.path.abspath(__file__))  # 当前文件的路径
        font = ImageFont.truetype(f'{file_path}/HYYakuHei-85W.ttf', self.size)

        # 创建画笔，Draw对象
        draw = ImageDraw.Draw(image)

        self.random_lines(draw)
        self.random_points(draw, 15)

        # 验证码值
        code = self.random_str()

        # 将验证码值绘制到图片中
        for i in range(self.length):
            draw.text((random.randint(30, 35) * i, random.randint(0, 5)), code[i], font=font,
                      fill=self.random_color(35, 150))

        # 模糊滤镜
        image = image.filter(ImageFilter.BLUR)
        return image, code